package example.demo.scope;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

/**
 * <? 友情提示BeanFactoryPostProcessor与BeanDefinitionRegistryPostProcessor的di是没有意义的【就是不会进行di】
 * <? di @Value[借助EnvironmentAware可以拿到配置文件的值],@Autowired,@Resource是无效的
 */
@Slf4j
@Component
public class CostumerScopeRegister implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
    public static ConfigurableListableBeanFactory configurableListableBeanFactory;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        CostumerScopeRegister.configurableListableBeanFactory = beanFactory;
        //@Scope("Xiao")缺省是singleton即单例
        beanFactory.registerScope("Xiao", new XiaoScope());
    }

    @Override
    public void setEnvironment(Environment environment) {
        if (environment instanceof StandardEnvironment) {
            StandardEnvironment standardEnvironment = (StandardEnvironment) environment;
            MutablePropertySources propertySources = standardEnvironment.getPropertySources();
            for (PropertySource<?> propertySource : propertySources) {
                String name = propertySource.getName();
                Object source = propertySource.getSource();
                // applicationConfig: [classpath:/application.properties]
                // applicationConfig: [classpath:/application.yaml]
                // 这很正常--肯定是没有application-dev.yaml的，因为没有spring.profiles.active=dev
                log.info("资源name--{}======{}\n", name, JSON.toJSON(source));
            }
        }
    }
}
